<template>
  <div>
    <h2>设备分配</h2>
    <el-form :model="assignmentForm" label-width="120px">
      <el-form-item label="设备">
        <el-select v-model="assignmentForm.deviceId" placeholder="请选择设备">
          <el-option
              v-for="device in devices"
              :key="device.deviceId"
              :label="device.deviceName"
              :value="device.deviceId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="分配类型">
        <el-select
            v-model="assignmentForm.assignType"
            placeholder="请选择分配类型"
            @change="handleAssignTypeChange"
        >
          <el-option label="用户" value="user"></el-option>
          <el-option label="部门" value="department"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="分配给">
        <el-select
            v-model="assignmentForm.assignedTo"
            placeholder="请选择使用人或部门"
        >
          <template v-if="assignmentForm.assignType === 'user'">
            <el-option
                v-for="user in users"
                :key="user.userId"
                :label="user.username"
                :value="user.userId"
            ></el-option>
          </template>
          <template v-else-if="assignmentForm.assignType === 'department'">
            <el-option
                v-for="department in departments"
                :key="department.departmentId"
                :label="department.departmentName"
                :value="department.departmentId"
            ></el-option>
          </template>
        </el-select>
      </el-form-item>
      <el-form-item label="分配日期">
        <el-date-picker
            v-model="assignmentForm.assignedDate"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitAssignment">提交分配</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { createAssignment } from '@/api/assignment.js';
import { getDepartments } from '@/api/departments.js';
import { getUsers } from '@/api/user.js';
import { queryDevicesInUse } from '@/api/device.js';

const devices = ref([]);
const departments = ref([]);
const users = ref([]);
const assignmentForm = ref({
  deviceId: '',
  assignedTo: '',
  assignType: '',
  assignedDate: '',
  assignerId: '当前用户ID', // 获取当前登录用户ID
});

onMounted(async () => {
  try {
    const deviceRes = await queryDevicesInUse({});
    if (deviceRes.code === 200) {
      devices.value = deviceRes.data;
    }
  } catch (error) {
    console.error('获取设备列表失败:', error);
  }
});

const handleAssignTypeChange = async (value) => {
  // 清空已选择的分配对象
  assignmentForm.value.assignedTo = '';

  if (value === 'user') {
    try {
      const userRes = await getUsers({});
      if (userRes.code === 200) {
        users.value = userRes.data;
      }
    } catch (error) {
      console.error('获取用户列表失败:', error);
    }
  } else if (value === 'department') {
    try {
      const departmentRes = await getDepartments({});
      if (departmentRes.code === 200) {
        departments.value = departmentRes.data;
      }
    } catch (error) {
      console.error('获取部门列表失败:', error);
    }
  }
};

const submitAssignment = async () => {
  try {
    const res = await createAssignment(assignmentForm.value);
    if (res.code === 200) {
      ElMessage.success('设备分配成功');
      // 重置表单
      Object.assign(assignmentForm.value, {
        deviceId: '',
        assignedTo: '',
        assignType: '',
        assignedDate: '',
      });
    }
  } catch (error) {
    ElMessage.error('设备分配失败: ' + error.message);
  }
};
</script>
